﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using ClientDataAccess;

namespace WinFormClient
{
    static class Program
    {
        static LoginForm LogForm = null;
        static DBO.Utility.PLICCredentials Credentials = null;
        static ClientSessionHandler SessionHandler = null;
        /// <summary>
        /// Point d'entrée principal de l'application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            SessionHandler = new ClientSessionHandler();
            Credentials = new DBO.Utility.PLICCredentials();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            LogForm = new LoginForm();
            LogForm.CenterForm();
            LogForm.Content = Credentials;
            
            LogForm.onLogIn += new EventHandler(LogForm_onLogIn);
            Application.Run(LogForm);
        }

        static void Run(string token)
        {
            MainForm MainForm = new MainForm();
            MainForm.Player = SessionHandler.GetPlayerInfo(token);

            MainForm.FormClosed += new FormClosedEventHandler(MainForm_FormClosed);

            MainForm.Show();
        }

        static void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            LogForm.Close();
            LogForm.Dispose();
        }

        static void LogForm_onLogIn(object sender, EventArgs e)
        {
            string token = null;
            if (Credentials.Login == "" || Credentials.Password == "")
                LogForm.Error = "Login and Password fields must not be empty.";
            else if ((token = SessionHandler.TryLogin(Credentials)) != null)
            {
                LogForm.Hide();
                Run(token);
            }
            else
                LogForm.Error = "Login failed. Please try again.";
        }
    }
}
